﻿using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System;
using UnityEditor;

namespace UnityEditor.XCodeEditor
{
	public class XUPE {

		// Modify one exist xCodeProject
		public static void ModXCodeProject(string xCodeProjectPath, string xupeModPath){
			XCProject xCodeProject = new XCProject(xCodeProjectPath);
			XUPEMod mod = new XUPEMod(xupeModPath);
			xCodeProject.ApplyXupemod(mod);
			
			xCodeProject.Save();
		}

		// Copy xCodeProject, and Modify copy
		public static void ExportFromXCodeProject(string sourceXCodeProjectPath, string xupeModPath, string targetXCodeProjectPath){
			DirectoryInfo sourceDi = new DirectoryInfo(sourceXCodeProjectPath);
			if(!sourceDi.Exists){
				throw new IOException( "'" + sourceXCodeProjectPath + "' not exists!");
			}
			DirectoryInfo modDi = new DirectoryInfo(xupeModPath);
			if(!modDi.Exists){
				throw new IOException( "'" + xupeModPath + "' not exists!");
			}
			DirectoryInfo targetDi = new DirectoryInfo(targetXCodeProjectPath);
			if(targetDi.Exists){
				Debug.Log("target exits, delete");
				targetDi.Delete(true);
			}
			Debug.Log("copying '" + sourceXCodeProjectPath + "' to '" + targetXCodeProjectPath + "'...");
			PShellUtil.CopyAll(sourceDi, targetDi);
			ModXCodeProject(targetXCodeProjectPath, xupeModPath);
		}

		// Tell Unity Engine to Build one xCodeProject, and modify it.
		public static void Export(string targetXCodeProjectPath, string xupeModPath){
			Debug.Log("Unity building xCode..."); 
			Build(targetXCodeProjectPath, UnityEditor.BuildTarget.iPhone, UnityEditor.BuildOptions.None);
			ModXCodeProject(targetXCodeProjectPath, xupeModPath);
		}

		private static string[] ListBuildScenes()
		{
			List<string> EditorScenes = new List<string>();
			foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes) 
			{
				if (!scene.enabled)
					continue;
				EditorScenes.Add(scene.path);
			}
			return EditorScenes.ToArray();
		}
		
		private static void Build(string target_dir, BuildTarget build_target, BuildOptions build_options)
		{
			string[] scenes = ListBuildScenes ();
			EditorUserBuildSettings.SwitchActiveBuildTarget(build_target);
			string res = BuildPipeline.BuildPlayer(scenes, target_dir, build_target, build_options);
			if (res.Length > 0)
			{
				throw new Exception("BuildPlayer failure: " + res);
			}
		}
	}
}